<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 配置 axios
axios.defaults.withCredentials = true  // 允许跨域携带 cookie
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'

// 内联实现 API 函数
function getWaitingPatients() {
  return axios.get('/api/patient/doctor/actions/waiting-patients/')
}

function callPatient(patientId: number) {
  return axios.post(`/api/patient/doctor/actions/call-patient/${patientId}/`)
}

function treatPatient(patientId: number) {
  return axios.post(`/api/patient/doctor/actions/treat-patient/${patientId}/`)
}

function saveDiagnosis(data: any) {
  return axios.post('/api/patient/doctor/actions/save-diagnosis/', data)
}

function getPatientDiagnoses(patientId: number, page: number = 1, pageSize: number = 10) {
  return axios.get(`/api/patient/doctor/actions/patient-diagnoses/${patientId}/`, {
    params: {
      page,
      page_size: pageSize
    }
  })
}

function getDiagnosedPatients() {
  return axios.get('/api/patient/patients/', {
    params: { status: 'diagnosed' }
  })
}

function getCompletedPatients() {
  return axios.get('/api/patient/patients/', {
    params: { status: 'completed' }
  })
}

function getCalledPatients() {
  return axios.get('/api/patient/patients/', {
    params: { status: 'called' }
  })
}

type PatientStatus = 'waiting' | 'called' | 'diagnosing' | 'completed';

interface Patient {
  id: number
  name: string
  gender: string
  age: number
  registration_time: string
  department: string
  doctor: string
  status: PatientStatus
  callTime?: string
  treatTime?: string
  diagnosis: string
  originalStatus?: PatientStatus
}

interface DiagnosisTemplate {
  id: number
  name: string
  description: string
  content: {
    chief_complaint: string
    present_illness: string
    past_history: string
    allergy_history: string
    physical_examination: string
    auxiliary_examination: string
    diagnosis: string
    treatment_plan: string
  }
}

interface HistoryDiagnosis {
  id: number
  created_at: string
  chief_complaint: string
  present_illness: string
  past_history: string
  allergy_history: string
  physical_examination: string
  auxiliary_examination: string
  diagnosis: string
  treatment_plan: string
  doctor_name: string
}

interface TemplateForm {
  name: string
  description: string
  content: {
    chief_complaint: string
    present_illness: string
    past_history: string
    allergy_history: string
    physical_examination: string
    auxiliary_examination: string
    diagnosis: string
    treatment_plan: string
  }
}

// 待诊患者列表
const waitingPatients = ref<Patient[]>([])

// 已叫号患者
const calledPatients = ref<Patient[]>([])

// 已就诊患者
const treatedPatients = ref<Patient[]>([])

// 已接诊患者
const diagnosedPatients = ref<Patient[]>([])

// 已完成患者
const completedPatients = ref<Patient[]>([])

// 当前选中的患者
const selectedPatient = ref<Patient | null>(null)

// 病历表单
const diagnosisForm = ref({
  patient: 0,
  chief_complaint: '', // 主诉
  present_illness: '', // 现病史
  past_history: '', // 既往史
  allergy_history: '', // 过敏史
  physical_examination: '', // 体格检查
  auxiliary_examination: '', // 辅助检查
  diagnosis: '', // 诊断
  treatment_plan: '' // 处理意见
})

// 添加新的响应式变量
const activeTab = ref('current')
const historyDiagnoses = ref<HistoryDiagnosis[]>([])
const diagnosisTemplates = ref<DiagnosisTemplate[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalHistoryDiagnoses = ref(0)
const templateDialogVisible = ref(false)
const templateForm = ref<TemplateForm>({
  name: '',
  description: '',
  content: {
    chief_complaint: '',
    present_illness: '',
    past_history: '',
    allergy_history: '',
    physical_examination: '',
    auxiliary_examination: '',
    diagnosis: '',
    treatment_plan: ''
  }
})

// 添加新的状态变量
const isReadOnly = ref(true) // 默认为只读模式
const loading = ref(false)

// 获取可用的状态选项
const getAvailableStatuses = (currentStatus: PatientStatus): PatientStatus[] => {
  const allStatuses: PatientStatus[] = ['waiting', 'called', 'diagnosing', 'completed'];
  return allStatuses;
}

// 统一使用小写状态值
const STATUS_MAPPING = {
  // 前端到后端
  frontToBack: {
    'waiting': 'waiting',
    'called': 'called',
    'diagnosing': 'diagnosing', 
    'completed': 'completed'
  },
  // 后端到前端 
  backToFront: {
    'waiting': 'waiting',
    'called': 'called',
    'diagnosing': 'diagnosing',
    'completed': 'completed'
  }
}

// 状态流转规则 - 允许所有状态之间的转换
const STATUS_TRANSITIONS: Record<Patient['status'], Patient['status'][]> = {
  'waiting': ['called', 'diagnosing', 'completed'],
  'called': ['waiting', 'diagnosing', 'completed'],
  'diagnosing': ['waiting', 'called', 'completed'],
  'completed': ['waiting', 'called', 'diagnosing']
}

// 处理状态映射
const mapPatientStatus = (patient: any): Patient => {
  if (patient.status) {
    // 确保状态值为小写
    patient.status = patient.status.toLowerCase();
  }
  return { ...patient } as Patient;
}

// 获取待诊患者列表
const fetchWaitingPatients = async () => {
  try {
    loading.value = true
    const response = await getWaitingPatients()
    
    // 处理状态映射
    waitingPatients.value = (response.data.results || []).map(mapPatientStatus);
    
    loading.value = false
  } catch (error) {
    console.error('获取待诊患者列表失败:', error)
    ElMessage.error('获取待诊患者列表失败')
    loading.value = false
  }
}

// 叫号
const callPatientAction = async (patient: Patient) => {
  if (patient.status !== 'waiting') {
    ElMessage.warning(`只能叫号待诊的患者，当前状态: ${patient.status}`)
    return
  }
  
  try {
    loading.value = true
    const response = await callPatient(patient.id)
    
    console.log('叫号响应:', response.data)
    
    if (response.data.success) {
      // 更新患者状态
      patient.status = 'called'
      patient.originalStatus = 'called' // 保存原始状态
      patient.callTime = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      
      // 从待诊列表移除
      waitingPatients.value = waitingPatients.value.filter(p => p.id !== patient.id)
      
      // 添加到已叫号列表
      calledPatients.value.push(patient)
      
      // 播放叫号声音
      playCallSound()
      
      ElMessage.success(`已叫号：${patient.name}`)
    } else {
      ElMessage.error(response.data.error || '叫号失败')
    }
    loading.value = false
  } catch (error: any) {
    console.error('叫号失败:', error)
    ElMessage.error(error.response?.data?.error || '叫号失败')
    loading.value = false
  }
}

// 接诊
const treatPatientAction = async (patient: Patient) => {
  if (patient.status !== 'called') {
    ElMessage.warning(`只能接诊已叫号的患者，当前状态: ${patient.status}`)
    return
  }
  
  try {
    loading.value = true
    const response = await treatPatient(patient.id)
    
    console.log('接诊响应:', response.data)
    
    if (response.data.success) {
      // 更新患者状态
      patient.status = 'diagnosing'
      patient.originalStatus = 'diagnosing' // 保存原始状态
      patient.treatTime = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      
      // 从已叫号列表移除
      calledPatients.value = calledPatients.value.filter(p => p.id !== patient.id)
      
      // 添加到已就诊列表
      treatedPatients.value.push(patient)
      
      // 选中当前患者并进入编辑模式
      selectedPatient.value = patient
      isReadOnly.value = false
      
      ElMessage.success(`已接诊：${patient.name}`)
    } else {
      ElMessage.error(response.data.error || '接诊失败')
    }
    loading.value = false
  } catch (error) {
    console.error('接诊失败:', error)
    ElMessage.error('接诊失败')
    loading.value = false
  }
}

// 播放叫号声音
const playCallSound = () => {
  // 实际项目中应该播放真实的叫号声音
  console.log('播放叫号声音')
}

// 选择患者
const selectPatient = async (patient: Patient) => {
  // 保存原始状态以便后续比较
  patient.originalStatus = patient.status
  
  selectedPatient.value = patient
  // 切换到只读模式
  isReadOnly.value = true
  
  try {
    loading.value = true
    const res = await getPatientDiagnoses(patient.id, 1, 1)
    if (res.data.results && res.data.results.length > 0) {
      const last = res.data.results[0]
      diagnosisForm.value = {
        patient: patient.id,
        chief_complaint: last.chief_complaint || '',
        present_illness: last.present_illness || '',
        past_history: last.past_history || '',
        allergy_history: last.allergy_history || '',
        physical_examination: last.physical_exam || '', // 注意这里使用physical_exam
        auxiliary_examination: last.auxiliary_exam || '', // 注意这里使用auxiliary_exam
        diagnosis: last.diagnosis || '',
        treatment_plan: last.treatment_plan || ''
      }
    } else {
      // 没有历史病历，清空
      diagnosisForm.value = {
        patient: patient.id,
        chief_complaint: '',
        present_illness: '',
        past_history: '',
        allergy_history: '',
        physical_examination: '',
        auxiliary_examination: '',
        diagnosis: '',
        treatment_plan: ''
      }
    }
    loading.value = false
  } catch (error) {
    console.error('获取患者历史诊断失败:', error)
    ElMessage.error('获取患者历史诊断失败')
    loading.value = false
  }
}

// 更新患者状态的函数
const updatePatientStatus = async (
  patient: Patient,
  oldStatus: PatientStatus | undefined,
  newStatus: PatientStatus
) => {
  if (!oldStatus) {
    oldStatus = patient.status;
  }
  
  try {
    // 发送状态更新请求到后端
    const response = await axios.patch(`/api/patient/patients/${patient.id}/`, {
      status: newStatus.toUpperCase()
    });

    if (response.status === 200) {
      // 从旧状态列表中移除
      switch(oldStatus) {
        case 'waiting':
          waitingPatients.value = waitingPatients.value.filter(p => p.id !== patient.id)
          break
        case 'called':
          calledPatients.value = calledPatients.value.filter(p => p.id !== patient.id)
          break
        case 'diagnosing':
          treatedPatients.value = treatedPatients.value.filter(p => p.id !== patient.id)
          break
      }
      
      // 添加到新状态列表
      switch(newStatus) {
        case 'waiting':
          waitingPatients.value.push(patient)
          break
        case 'called':
          calledPatients.value.push(patient)
          break
        case 'diagnosing':
          treatedPatients.value.push(patient)
          break
      }

      ElMessage.success(`患者状态已更新为${getStatusText(newStatus)}`)
    }
  } catch (error) {
    console.error('更新患者状态失败:', error)
    ElMessage.error('更新患者状态失败')
    throw error
  }
}

// 修改保存病历函数，考虑只读模式
const saveDiagnosisAction = async () => {
  if (!selectedPatient.value) {
    ElMessage.warning('请先选择患者')
    return
  }
  
  if (isReadOnly.value) {
    ElMessage.warning('当前为只读模式，请点击"编辑病历"按钮进行编辑')
    return
  }
  
  try {
    loading.value = true
    // 获取 CSRF 令牌
    const csrftoken = document.cookie.split('; ')
      .find(row => row.startsWith('csrftoken='))
      ?.split('=')[1]
    
    // 获取会话 ID
    const sessionid = document.cookie.split('; ')
      .find(row => row.startsWith('sessionid='))
      ?.split('=')[1]
    
    const diagnosisData = {
      patient: selectedPatient.value.id,
      chief_complaint: diagnosisForm.value.chief_complaint || '无',
      present_illness: diagnosisForm.value.present_illness || '无',
      past_history: diagnosisForm.value.past_history || '无',
      allergy_history: diagnosisForm.value.allergy_history || '无',
      physical_examination: diagnosisForm.value.physical_examination || '无特殊',
      auxiliary_examination: diagnosisForm.value.auxiliary_examination || '无',
      diagnosis: diagnosisForm.value.diagnosis || '待诊断',
      treatment_plan: diagnosisForm.value.treatment_plan || '待制定'
    }
    
    console.log('发送的诊断数据:', diagnosisData)
    
    // 使用fetch替代axios
    const response = await fetch('/api/patient/doctor/actions/save-diagnosis/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': csrftoken || '',
        'Cookie': `sessionid=${sessionid || ''}`
      },
      credentials: 'include',
      body: JSON.stringify(diagnosisData)
    })
    
    const data = await response.json()
    
    if (response.ok) {
      ElMessage.success('病历保存成功')
      
      // 切换回只读模式
      isReadOnly.value = true
      
      // 更新患者状态
      if (selectedPatient.value) {
        selectedPatient.value.status = 'completed'
        selectedPatient.value.originalStatus = 'completed'
        
        // 从已就诊列表移除
        treatedPatients.value = treatedPatients.value.filter(p => p.id !== selectedPatient.value!.id)
        
        // 添加到已完成列表
        completedPatients.value.push(selectedPatient.value)
        
        // 更新后端状态 - 直接使用大写状态值
        try {
          const statusResponse = await axios.patch(`/api/patient/patients/${selectedPatient.value.id}/`, {
            status: 'COMPLETED'
          })
          if (statusResponse.status === 200) {
            console.log('成功更新患者状态为已完成')
          }
        } catch (error) {
          console.error('更新患者状态失败:', error)
        }
      }
      
      // 刷新历史病历
      if (activeTab.value === 'history') {
        fetchHistoryDiagnoses()
      }
    } else {
      ElMessage.error(data.error || '保存病历失败')
    }
    loading.value = false
  } catch (error: any) {
    console.error('保存病历失败:', error)
    ElMessage.error(error.message || '保存病历失败')
    loading.value = false
  }
}

// 刷新待诊列表
const refreshWaitingList = () => {
  fetchWaitingPatients()
  ElMessage.success('已刷新待诊列表')
}

// 获取已叫号患者
const fetchCalledPatients = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/patient/patients/', {
      params: { status: 'CALLED' }
    })
    
    calledPatients.value = (response.data.results || [])
      .map(mapPatientStatus)
      .filter((patient: Patient) => patient.status.toLowerCase() === 'called')
    
    loading.value = false
  } catch (error) {
    console.error('获取已叫号患者失败:', error)
    ElMessage.error('获取已叫号患者失败')
    loading.value = false
  }
}

// 获取诊断中患者
const fetchDiagnosedPatients = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/patient/patients/', {
      params: { status: 'DIAGNOSING' }
    })
    
    treatedPatients.value = (response.data.results || [])
      .map(mapPatientStatus)
      .filter((patient: Patient) => patient.status.toLowerCase() === 'diagnosing')
    
    loading.value = false
  } catch (error) {
    console.error('获取诊断中患者失败:', error)
    ElMessage.error('获取诊断中患者失败')
    loading.value = false
  }
}

// 添加新的方法
const fetchHistoryDiagnoses = async () => {
  if (!selectedPatient.value) return
  try {
    loading.value = true
    console.log('获取历史病历，参数:', {
      patientId: selectedPatient.value.id,
      page: currentPage.value,
      pageSize: pageSize.value
    })
    const response = await getPatientDiagnoses(selectedPatient.value.id, currentPage.value, pageSize.value)
    console.log('历史病历原始数据:', response.data)
    
    // 确保每个字段都有值，并正确映射字段名
    historyDiagnoses.value = response.data.results.map((item: any) => ({
      id: item.id,
      created_at: item.created_at,
      chief_complaint: item.chief_complaint || '',
      present_illness: item.present_illness || '',
      past_history: item.past_history || '',
      allergy_history: item.allergy_history || '',
      physical_examination: item.physical_exam || '',  // 注意这里使用physical_exam
      auxiliary_examination: item.auxiliary_exam || '', // 注意这里使用auxiliary_exam
      diagnosis: item.diagnosis || '',
      treatment_plan: item.treatment_plan || '',
      doctor_name: item.doctor_name || ''
    }))
    
    totalHistoryDiagnoses.value = response.data.count
    loading.value = false
  } catch (error) {
    console.error('获取历史病历失败:', error)
    ElMessage.error('获取历史病历失败')
    loading.value = false
  }
}

const viewHistoryDiagnosis = (diagnosis: HistoryDiagnosis) => {
  console.log('查看历史病历原始数据:', diagnosis)
  
  // 填充表单数据前先设置为只读模式
  isReadOnly.value = true
  
  // 克隆一份数据，避免引用问题
  const historyData = {
    chief_complaint: diagnosis.chief_complaint || '',
    present_illness: diagnosis.present_illness || '',
    past_history: diagnosis.past_history || '',
    allergy_history: diagnosis.allergy_history || '',
    physical_examination: diagnosis.physical_examination || '',
    auxiliary_examination: diagnosis.auxiliary_examination || '',
    diagnosis: diagnosis.diagnosis || '',
    treatment_plan: diagnosis.treatment_plan || ''
  }
  
  // 打印每个字段检查是否有效
  console.log('历史病历字段值检查:')
  Object.entries(historyData).forEach(([key, value]) => {
    console.log(`${key}: ${value}`)
  })
  
  // 将历史病历内容填充到当前表单
  diagnosisForm.value = {
    patient: selectedPatient.value!.id,
    ...historyData
  }
  
  console.log('填充后的表单数据:', diagnosisForm.value)
  
  // 切换到当前诊断标签查看详细内容
  activeTab.value = 'current'
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchHistoryDiagnoses()
}

const fetchDiagnosisTemplates = async () => {
  try {
    // 获取 CSRF 令牌
    const csrftoken = document.cookie.split('; ')
      .find(row => row.startsWith('csrftoken='))
      ?.split('=')[1]
    
    // 获取会话 ID
    const sessionid = document.cookie.split('; ')
      .find(row => row.startsWith('sessionid='))
      ?.split('=')[1]
    
    // 添加认证信息
    const response = await fetch('/api/doctor/diagnosis-templates/', {
      headers: {
        'X-CSRFToken': csrftoken || '',
        'Cookie': `sessionid=${sessionid || ''}`
      },
      credentials: 'include'
    })
    const data = await response.json()
    diagnosisTemplates.value = Array.isArray(data) ? data : (data.results || [])
  } catch (error) {
    console.error('获取诊断模板失败:', error)
    ElMessage.error('获取诊断模板失败')
  }
}

const applyTemplate = (template: DiagnosisTemplate) => {
  diagnosisForm.value = {
    ...diagnosisForm.value,
    chief_complaint: template.content.chief_complaint,
    present_illness: template.content.present_illness,
    past_history: template.content.past_history,
    allergy_history: template.content.allergy_history,
    physical_examination: template.content.physical_examination,
    auxiliary_examination: template.content.auxiliary_examination,
    diagnosis: template.content.diagnosis,
    treatment_plan: template.content.treatment_plan
  }
  ElMessage.success('模板应用成功')
}

const createTemplate = async () => {
  try {
    // 获取 CSRF 令牌
    const csrftoken = document.cookie.split('; ')
      .find(row => row.startsWith('csrftoken='))
      ?.split('=')[1]
    
    // 获取会话 ID
    const sessionid = document.cookie.split('; ')
      .find(row => row.startsWith('sessionid='))
      ?.split('=')[1]
    
    // 添加认证信息
    const response = await fetch('/api/doctor/diagnosis-templates/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': csrftoken || '',
        'Cookie': `sessionid=${sessionid || ''}`
      },
      credentials: 'include',
      body: JSON.stringify(templateForm.value)
    })
    if (response.ok) {
      ElMessage.success('模板创建成功')
      templateDialogVisible.value = false
      fetchDiagnosisTemplates()
    } else {
      ElMessage.error('模板创建失败')
    }
  } catch (error) {
    console.error('创建模板失败:', error)
    ElMessage.error('创建模板失败')
  }
}

const deleteTemplate = async (template: DiagnosisTemplate) => {
  try {
    // 获取 CSRF 令牌
    const csrftoken = document.cookie.split('; ')
      .find(row => row.startsWith('csrftoken='))
      ?.split('=')[1]
    
    // 获取会话 ID
    const sessionid = document.cookie.split('; ')
      .find(row => row.startsWith('sessionid='))
      ?.split('=')[1]
    
    // 添加认证信息
    const response = await fetch(`/api/doctor/diagnosis-templates/${template.id}/`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': csrftoken || '',
        'Cookie': `sessionid=${sessionid || ''}`
      },
      credentials: 'include'
    })
    if (response.ok) {
      ElMessage.success('模板删除成功')
      fetchDiagnosisTemplates()
    } else {
      ElMessage.error('模板删除失败')
    }
  } catch (error) {
    console.error('删除模板失败:', error)
    ElMessage.error('删除模板失败')
  }
}

const saveAsTemplate = () => {
  templateForm.value = {
    name: '',
    description: '从当前诊断保存的模板',
    content: {
      chief_complaint: diagnosisForm.value.chief_complaint,
      present_illness: diagnosisForm.value.present_illness,
      past_history: diagnosisForm.value.past_history,
      allergy_history: diagnosisForm.value.allergy_history,
      physical_examination: diagnosisForm.value.physical_examination,
      auxiliary_examination: diagnosisForm.value.auxiliary_examination,
      diagnosis: diagnosisForm.value.diagnosis,
      treatment_plan: diagnosisForm.value.treatment_plan
    }
  }
  templateDialogVisible.value = true
}

// 监听标签页变化
watch(activeTab, (newTab) => {
  if (newTab === 'history') {
    fetchHistoryDiagnoses()
  } else if (newTab === 'templates') {
    fetchDiagnosisTemplates()
  }
})

// 监听选中患者变化
watch(selectedPatient, (newPatient) => {
  if (newPatient && activeTab.value === 'history') {
    fetchHistoryDiagnoses()
  }
})

// 获取已完成患者
const fetchCompletedPatients = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/patient/patients/', {
      params: { status: 'completed' } // 使用小写
    })
    
    // 处理状态映射并筛选
    completedPatients.value = (response.data.results || [])
      .map(mapPatientStatus)
      .filter((patient: Patient) => patient.status === 'completed')
    
    loading.value = false
  } catch (error) {
    console.error('获取已完成患者失败:', error)
    ElMessage.error('获取已完成患者失败')
    loading.value = false
  }
}

// 初始化数据
onMounted(() => {
  console.log('组件挂载，开始获取数据')
  fetchWaitingPatients()
  fetchCalledPatients()
  fetchDiagnosedPatients()
  fetchCompletedPatients()
  fetchDiagnosisTemplates()
  
  // 添加定时刷新，但使用单个定时器，避免重复请求
  const refreshInterval = setInterval(() => {
    console.log('执行定时刷新')
    // 只获取必要数据，减少请求数量
    fetchWaitingPatients()
  }, 60000) // 改为60秒刷新一次，只刷新待诊列表
  
  // 组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(refreshInterval)
  })
})

// 格式化时间的函数
function formatDateTime(dateStr: string) {
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-');
}

// 添加获取状态标签类型的方法
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'waiting': return 'info'
    case 'called': return 'warning'
    case 'diagnosing': return 'primary'
    case 'completed': return 'success'
    default: return 'info'
  }
}

// 获取状态文本的方法
const getStatusText = (status: PatientStatus): string => {
  switch (status) {
    case 'waiting': return '待诊'
    case 'called': return '已叫号'
    case 'diagnosing': return '诊断中'
    case 'completed': return '已完成'
    default: return '未知'
  }
}

// 切换编辑模式
const toggleEditMode = () => {
  isReadOnly.value = !isReadOnly.value
}

// 选择历史病例点击查看按钮的函数
const viewHistoryTab = () => {
  activeTab.value = 'history'
  fetchHistoryDiagnoses()
}
</script>

<template>
  <div class="call-view">
    <el-row :gutter="20">
      <!-- 左侧患者列表 -->
      <el-col :span="8">
        <el-card class="patient-list">
          <template #header>
            <div class="card-header">
              <span>待诊患者</span>
              <el-button type="primary" size="small" @click="refreshWaitingList">刷新</el-button>
            </div>
          </template>
          <el-table :data="waitingPatients" style="width: 100%" @row-click="selectPatient" :height="250">
            <el-table-column prop="name" label="姓名" width="80" />
            <el-table-column prop="gender" label="性别" width="60">
              <template #default="scope">
                {{ scope.row.gender === 'M' ? '男' : '女' }}
              </template>
            </el-table-column>
            <el-table-column prop="age" label="年龄" width="60" />
            <el-table-column prop="registration_time" label="挂号时间" min-width="150">
              <template #default="scope">
                {{ formatDateTime(scope.row.registration_time) }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="80">
              <template #default="scope">
                <el-button link type="primary" size="small" @click.stop="callPatientAction(scope.row)">叫号</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-card class="patient-list">
          <template #header>
            <div class="card-header">
              <span>已叫号患者</span>
              <el-button type="primary" size="small" @click="fetchCalledPatients">刷新</el-button>
            </div>
          </template>
          <el-table :data="calledPatients" style="width: 100%" @row-click="selectPatient" :height="200">
            <el-table-column prop="name" label="姓名" width="80" />
            <el-table-column prop="gender" label="性别" width="60">
              <template #default="scope">
                {{ scope.row.gender === 'M' ? '男' : '女' }}
              </template>
            </el-table-column>
            <el-table-column prop="age" label="年龄" width="60" />
            <el-table-column prop="callTime" label="叫号时间" min-width="150" />
            <el-table-column fixed="right" label="操作" width="80">
              <template #default="scope">
                <el-button link type="primary" size="small" @click.stop="treatPatientAction(scope.row)">接诊</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-card class="patient-list">
          <template #header>
            <div class="card-header">
              <span>诊断中患者</span>
              <el-button type="primary" size="small" @click="fetchDiagnosedPatients">刷新</el-button>
            </div>
          </template>
          <el-table :data="treatedPatients" style="width: 100%" @row-click="selectPatient" :height="200">
            <el-table-column prop="name" label="姓名" width="80" />
            <el-table-column prop="gender" label="性别" width="60">
              <template #default="scope">
                {{ scope.row.gender === 'M' ? '男' : '女' }}
              </template>
            </el-table-column>
            <el-table-column prop="age" label="年龄" width="60" />
            <el-table-column prop="treatTime" label="就诊时间" width="120" />
            <el-table-column fixed="right" label="操作" width="100">
              <template #default="scope">
                <el-button type="info" size="small" @click.stop="selectPatient(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        
        <el-card class="patient-list">
          <template #header>
            <div class="card-header">
              <span>已完成接诊</span>
              <el-button type="primary" size="small" @click="fetchCompletedPatients">刷新</el-button>
            </div>
          </template>
          <el-table :data="completedPatients" style="width: 100%" @row-click="selectPatient" :height="200">
            <el-table-column prop="name" label="姓名" width="80" />
            <el-table-column prop="gender" label="性别" width="60">
              <template #default="scope">
                {{ scope.row.gender === 'M' ? '男' : '女' }}
              </template>
            </el-table-column>
            <el-table-column prop="age" label="年龄" width="60" />
            <el-table-column prop="diagnosis" label="诊断" min-width="120" />
            <el-table-column fixed="right" label="操作" width="100">
              <template #default="scope">
                <el-button type="info" size="small" @click.stop="selectPatient(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧病历单 -->
      <el-col :span="16">
        <el-card class="diagnosis-form" v-loading="loading">
          <template #header>
            <div class="card-header">
              <span>病历单</span>
              <div class="button-group">
                <el-button v-if="isReadOnly && selectedPatient" type="primary" @click="toggleEditMode">编辑病历</el-button>
                <el-button v-if="selectedPatient" type="info" @click="viewHistoryTab">历史病例</el-button>
                <el-button v-if="!isReadOnly" type="success" @click="saveDiagnosisAction">保存病历</el-button>
                <el-button v-if="!isReadOnly" type="info" @click="toggleEditMode">取消编辑</el-button>
              </div>
            </div>
          </template>
          
          <div v-if="selectedPatient" class="patient-info">
            <el-descriptions :column="3" border>
              <el-descriptions-item label="姓名">{{ selectedPatient.name }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ selectedPatient.gender === 'M' ? '男' : '女' }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{ selectedPatient.age }}</el-descriptions-item>
              <el-descriptions-item label="科室">{{ selectedPatient.department }}</el-descriptions-item>
              <el-descriptions-item label="医生">{{ selectedPatient.doctor }}</el-descriptions-item>
              <el-descriptions-item label="挂号时间">{{ formatDateTime(selectedPatient.registration_time) }}</el-descriptions-item>
            </el-descriptions>
            
            <div class="patient-status-panel">
              <span class="label">患者状态:</span>
              <el-tag 
                :type="getStatusTagType(selectedPatient.status)" 
                size="default"
              >
                {{ getStatusText(selectedPatient.status) }}
              </el-tag>
              <div class="status-change">
                <el-select 
                  v-model="selectedPatient.status" 
                  size="default" 
                  style="width: 120px"
                >
                  <el-option 
                    v-for="status in getAvailableStatuses(selectedPatient.status as PatientStatus)"
                    :key="status"
                    :label="getStatusText(status)"
                    :value="status"
                  />
                </el-select>
                <el-button type="primary" @click="updatePatientStatus(selectedPatient, selectedPatient.originalStatus as PatientStatus, selectedPatient.status as PatientStatus)">更新状态</el-button>
              </div>
            </div>
          </div>
          
          <div v-else class="no-patient">
            <el-empty description="请选择患者" />
          </div>
          
          <el-tabs v-model="activeTab" class="diagnosis-tabs">
            <el-tab-pane label="当前诊断" name="current">
              <el-form v-if="selectedPatient" :model="diagnosisForm" label-width="100px" class="diagnosis-form-content">
                <el-form-item label="主诉">
                  <el-input v-model="diagnosisForm.chief_complaint" type="textarea" :rows="2" placeholder="请输入主诉" :readonly="isReadOnly" />
                </el-form-item>
                
                <el-form-item label="现病史">
                  <el-input v-model="diagnosisForm.present_illness" type="textarea" :rows="3" placeholder="请输入现病史" :readonly="isReadOnly" />
                </el-form-item>
                
                <el-form-item label="既往史">
                  <el-input v-model="diagnosisForm.past_history" type="textarea" :rows="2" placeholder="请输入既往史" :readonly="isReadOnly" />
                </el-form-item>
                
                <el-form-item label="过敏史">
                  <el-input v-model="diagnosisForm.allergy_history" type="textarea" :rows="2" placeholder="请输入过敏史" :readonly="isReadOnly" />
                </el-form-item>
                
                <el-form-item label="体格检查">
                  <el-input v-model="diagnosisForm.physical_examination" type="textarea" :rows="3" placeholder="请输入体格检查结果" :readonly="isReadOnly" />
                </el-form-item>
                
                <el-form-item label="辅助检查">
                  <el-input v-model="diagnosisForm.auxiliary_examination" type="textarea" :rows="3" placeholder="请输入辅助检查结果" :readonly="isReadOnly" />
                </el-form-item>
                
                <el-form-item label="诊断">
                  <el-input v-model="diagnosisForm.diagnosis" type="textarea" :rows="2" placeholder="请输入诊断结果" :readonly="isReadOnly" />
                </el-form-item>
                
                <el-form-item label="处理意见">
                  <el-input v-model="diagnosisForm.treatment_plan" type="textarea" :rows="3" placeholder="请输入处理意见" :readonly="isReadOnly" />
                </el-form-item>
              </el-form>
            </el-tab-pane>
            
            <el-tab-pane label="历史病历" name="history">
              <div v-if="selectedPatient">
                <el-table :data="historyDiagnoses" style="width: 100%">
                  <el-table-column prop="created_at" label="诊断日期" width="180" />
                  <el-table-column prop="chief_complaint" label="主诉" />
                  <el-table-column prop="present_illness" label="现病史" />
                  <el-table-column prop="diagnosis" label="诊断" />
                  <el-table-column prop="doctor_name" label="医生" width="120" />
                  <el-table-column fixed="right" label="操作" width="120">
                    <template #default="scope">
                      <el-button link type="primary" @click="viewHistoryDiagnosis(scope.row)">查看</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="pagination">
                  <el-pagination
                    v-model:current-page="currentPage"
                    :page-size="pageSize"
                    :total="totalHistoryDiagnoses"
                    layout="prev, pager, next"
                    @current-change="handlePageChange"
                  />
                </div>
              </div>
              <div v-else>
                <el-empty description="请先选择患者" />
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="诊断模板" name="templates">
              <div class="template-actions">
                <el-button type="primary" @click="saveAsTemplate">保存为模板</el-button>
              </div>
              <el-table :data="diagnosisTemplates" style="width: 100%">
                <el-table-column prop="name" label="模板名称" />
                <el-table-column prop="description" label="描述" />
                <el-table-column fixed="right" label="操作" width="200">
                  <template #default="scope">
                    <el-button link type="primary" @click="applyTemplate(scope.row)">应用</el-button>
                    <el-button link type="danger" @click="deleteTemplate(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
    
    <el-dialog
      v-model="templateDialogVisible"
      title="保存诊断模板"
      width="50%"
    >
      <el-form :model="templateForm" label-width="100px">
        <el-form-item label="模板名称">
          <el-input v-model="templateForm.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板描述">
          <el-input v-model="templateForm.description" type="textarea" :rows="2" placeholder="请输入模板描述" />
        </el-form-item>
        <el-form-item label="主诉">
          <el-input v-model="templateForm.content.chief_complaint" type="textarea" :rows="2" placeholder="请输入主诉" />
        </el-form-item>
        <el-form-item label="现病史">
          <el-input v-model="templateForm.content.present_illness" type="textarea" :rows="3" placeholder="请输入现病史" />
        </el-form-item>
        <el-form-item label="既往史">
          <el-input v-model="templateForm.content.past_history" type="textarea" :rows="2" placeholder="请输入既往史" />
        </el-form-item>
        <el-form-item label="过敏史">
          <el-input v-model="templateForm.content.allergy_history" type="textarea" :rows="2" placeholder="请输入过敏史" />
        </el-form-item>
        <el-form-item label="体格检查">
          <el-input v-model="templateForm.content.physical_examination" type="textarea" :rows="3" placeholder="请输入体格检查结果" />
        </el-form-item>
        <el-form-item label="辅助检查">
          <el-input v-model="templateForm.content.auxiliary_examination" type="textarea" :rows="3" placeholder="请输入辅助检查结果" />
        </el-form-item>
        <el-form-item label="诊断">
          <el-input v-model="templateForm.content.diagnosis" type="textarea" :rows="2" placeholder="请输入诊断结果" />
        </el-form-item>
        <el-form-item label="处理意见">
          <el-input v-model="templateForm.content.treatment_plan" type="textarea" :rows="3" placeholder="请输入处理意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="templateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createTemplate">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.call-view {
  padding: 20px;
  height: calc(100vh - 84px);
  overflow: hidden;
}

.patient-list {
  margin-bottom: 20px;
}

/* 修改左侧栏样式，使其可滚动 */
.el-col:first-child {
  height: calc(100vh - 84px);
  overflow-y: auto;
  padding-right: 10px;
}

/* 设置表格最大高度，使其在卡片内可滚动 */
:deep(.el-table__body-wrapper) {
  max-height: 200px !important;
  overflow-y: auto !important;
}

.diagnosis-form {
  height: calc(100vh - 104px);
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  background: #fff;
  z-index: 1;
}

.el-table {
  margin-top: 10px;
}

.patient-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.no-patient {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.diagnosis-form-content {
  margin-top: 20px;
  padding: 20px;
}

/* 只读表单样式 */
.diagnosis-form-content :deep(.el-textarea__inner[readonly]) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
  cursor: default;
}

.diagnosis-form-content :deep(.el-input__inner[readonly]) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

.diagnosis-tabs {
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.template-actions {
  margin-bottom: 20px;
}

/* 状态选择器样式 */
.patient-status-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  gap: 10px;
}

.patient-status-panel {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  padding: 10px 15px;
  border-radius: 4px;
  margin-top: 10px;
}

.patient-status-panel .label {
  font-weight: bold;
  margin-right: 10px;
}

.status-change {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 10px;
}
</style> 